//
// Created by mouse on 2019/10/8.
//
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

#include "app.h"

HTTPClient httpClient;
WiFiClient wiFiClient;

String getLocalOutIp()
{
    String ip;

    httpClient.begin(wiFiClient, IP_URL);
    int httpCode = httpClient.GET();
    if (httpCode == HTTP_CODE_OK)
    {
        String payload = httpClient.getString();
        Serial.println(payload);

        DynamicJsonDocument doc(1024);
        deserializeJson(doc, payload);
        JsonObject obj = doc.as<JsonObject>();
        ip = obj["query"].as<String>();
    }
    httpClient.end();

    return ip;

//    MatchState ms;
//
//    httpClient.begin(wiFiClient, "http://ip-api.com/json");
//    int httpCode = httpClient.GET();
//    if (httpCode == HTTP_CODE_OK)
//    {
//        String payload = httpClient.getString();
//        Serial.println(payload);
//
//        char tag[payload.length() + 1];
//        payload.toCharArray(tag, payload.length());
//        ms.Target(tag);
//    }
//    httpClient.end();
//
//    char result = ms.Match("(%d+)");
//    if (result == REGEXP_MATCHED)
//    {
//        char buf[100];
//        Serial.print("Matched on: ");
//        Serial.println(ms.GetMatch(buf));
//    } else
//    {
//        Serial.println("No match.");
//    }
}

void print_wifi()
{
    Serial.printf("====================================\n");
    Serial.printf("Chip ID: %d\n", ESP.getChipId());
    Serial.printf("ESP8266 mode is: %d\n", WiFi.getMode());
    Serial.printf("MAC address is: %s\n", WiFi.macAddress().c_str());
    Serial.printf("IP is: %s\n", WiFi.localIP().toString().c_str());
    Serial.printf("====================================\n");
}

void wifi_connect()
{
    //设置WiFi模式
    WiFi.mode(WIFI_STA);
    //扫描并连接WiFi
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.printf("\nConnecting to %s ...", WIFI_SSID);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.print(".");
    }
    Serial.println();
}

void app_setup()
{

}

void app_loop()
{
    if (WiFi.status() != WL_CONNECTED)
    {
        wifi_connect();
        print_wifi();
    }

    getLocalOutIp();
    delay(10000);

}
